﻿using System.IO;
using WpfApp.Exceptions;
using WpfApp.SaveInfos;

namespace WpfApp.Uers
{
    public class UserManager
    {
        private static string SaveInfoFileName = "Users.json";

        public List<User> Users { get; private set; }

        public UserManager()
        {
            Users = GetUsersFromFile();
        }

        public bool Auth(string userId, out User user)
        {
            user = this.Users.FirstOrDefault(item =>
            {
                return item.UserId == userId;
            })!;

            return user != null;
        }

        public void AddUser(User user)
        {
            if (Users.Any(item =>
            {
                return user.UserId == user.UserId;
            }))
            {
                throw new UserFriendlyException("卡号已经被注册！");
            }

            Users.Add(user);
            SaveToFile();
        }

        public void RemoveUser(string userId)
        {
            var index = Users.FindIndex(item => item.UserId == userId);

            if (index >= 0)
            {
                Users.RemoveAt(index);
                SaveToFile();
            }
        }

        private void SaveToFile()
        {
            var path = Path.Combine(AppContext.BaseDirectory, SaveInfoFileName);
            SaveInfo.Write(this.Users, path);
        }

        private List<User> GetUsersFromFile()
        {
            var path = Path.Combine(AppContext.BaseDirectory, SaveInfoFileName);
            return SaveInfo.Read<List<User>>(path) ?? new() { new() { UserId = "123456", Name = "admin" } };
        }
    }
}
